import asyncio
from time import sleep

import websockets

connected_clients = set()

async def server(websocket, path):
    connected_clients.add(websocket)
    try:
        while True:
            message = await websocket.recv()   # 接收消息
            print(f"Received message from client: {message}")
            await websocket.send("This is a server message.")  # 发送服务器消息给客户端
    except websockets.exceptions.ConnectionClosed:
        print("Client disconnected")
    finally:
        connected_clients.remove(websocket)  # 客户端断开连接时，从集合中移除

async def send_message_to_client(message):
    for client in connected_clients:   # 向所有连接的客户端发送消息
        await client.send(message)

async def send_messages_periodically():
    count = 0   # 定期发送消息示例
    while True:
        await asyncio.sleep(3)   # 每3秒发送一次
        count += 1
        message = f"这是第 {count} 次定期发送的消息"
        print(f"这是第 {count} 次定期发送的消息")
        await send_message_to_client(message)

async def main():
    start_server = websockets.serve(server, '192.168.213.20', 8765)
    server_task = await asyncio.ensure_future(start_server)  # 启动WebSocket服务器
    # sleep(3)
    sender_task = await asyncio.ensure_future(send_messages_periodically())   # 启动定期发送消息的任务
    await server_task   # 等待服务器任务完成

asyncio.run(main())